
#include "driver/gpio.h"
#include "driver/twai.h"
#include "esp_log.h"

#define EXAMPLE_TAG             "Can Master"

void canInit()
{
    //Initialize configuration structures using macro initializers
    twai_general_config_t g_config = TWAI_GENERAL_CONFIG_DEFAULT(GPIO_NUM_1, GPIO_NUM_2, TWAI_MODE_NORMAL);
    twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS();
    twai_filter_config_t f_config = TWAI_FILTER_CONFIG_ACCEPT_ALL();

    //Install TWAI driver
    ESP_ERROR_CHECK(twai_driver_install(&g_config, &t_config, &f_config));
    ESP_LOGI(EXAMPLE_TAG, "Driver installed");
    ESP_ERROR_CHECK(twai_start());
    ESP_LOGI(EXAMPLE_TAG, "Driver started");

    /******************************** */ /**
     *     暂时没想好，但也不想让他跑【以下代码】
     */ /******************************** */
    void func_no_use()
    {   ESP_ERROR_CHECK(twai_stop());
        ESP_LOGI(EXAMPLE_TAG, "Driver stopped");
        //Uninstall TWAI driver
        ESP_ERROR_CHECK(twai_driver_uninstall());
        ESP_LOGI(EXAMPLE_TAG, "Driver uninstalled");
    }
}




void fillTwaiMsg(twai_message_t* tx_msg, uint32_t frame_id, uint8_t dlc, uint8_t* frame_data)
{
    tx_msg->identifier = frame_id;
    tx_msg->data_length_code = dlc;
    //
    for (int i=0; i<=dlc-1; i++) {
        tx_msg->data [i] = frame_data[i];
    }
}

#define TWAI_TX_MSG_DEFAULT_CONFIG() {.ss = 1}

void canWrite(uint32_t frame_id, uint8_t dlc, uint8_t* frame_data)
{
    twai_message_t tx_msg = TWAI_TX_MSG_DEFAULT_CONFIG();  //
    fillTwaiMsg(&tx_msg, frame_id, dlc, frame_data);           
    twai_transmit(&tx_msg, portMAX_DELAY);
    vTaskDelay(pdMS_TO_TICKS(10));
}

void canRead(uint32_t *frame_id, uint8_t *dlc, uint8_t* frame_data)
{
    twai_message_t rx_msg;
    twai_receive(&rx_msg, portMAX_DELAY);

    (*frame_id) = rx_msg.identifier;
    (*dlc) = rx_msg.data_length_code;
    for (int i=0; i<=rx_msg.data_length_code-1; i++) {
        frame_data[i] = rx_msg.data[i];
    }
    vTaskDelay(pdMS_TO_TICKS(10));
}












